﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;

namespace UniversityCourses.Models
{
    //using Repository design pattern for testability  
    public class UniversityCoursesRepository : IUniversityCoursesRepository
    {
        private UniversityCoursesEntities db = new UniversityCoursesEntities();

        public bool StudentExists(string email)
        {
            return db.Students.Any(p => p.Email.ToLower() == email.ToLower());
        }

        public void CreateStudent(string email, string provider, string providerUserId)
        {
            db.Students.AddObject(new Student { Email = email });
            db.SaveChanges();

            OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, email);
            OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
        }

        public Student GetStudentByEmail(string email)
        {
            return db.Students.FirstOrDefault(p => p.Email.ToLower() == email.ToLower()); 
        }
        
        public IEnumerable<Course> GetAllCourses()
        {
            return db.Courses.AsParallel().ToList();
        }

        public IEnumerable<int> GetCoursesByStudentEmail(string email)
        {
            Student student = this.GetStudentByEmail(email);
            return student.StudentCourses.Select(p => p.CourseId).ToList();
        }

        public Course GetCoursesById(int id)
        {
            return db.Courses.FirstOrDefault(p => p.Id == id);
        }

        public void UpdateCourse(Course course)
        {
            Course courseToUpdate = this.GetCoursesById(course.Id);
            courseToUpdate.Name = course.Name;
            db.SaveChanges();
        }

        public void DeleteCourse(int id)
        {
            db.Courses.DeleteObject(this.GetCoursesById(id));
            db.SaveChanges();
        }

        public void CreateCourse(Course course)
        {
            db.Courses.AddObject(course);
            db.SaveChanges();
        }

        public void Register(int id, string studentEmail)
        {
            StudentCourse sc = new StudentCourse();
            sc.CourseId = id;
            sc.StudentId = this.GetStudentByEmail(studentEmail).UserId;
            db.StudentCourses.AddObject(sc);
            db.SaveChanges();
        }
    }
}